package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper roleresourceMapper;

    @Override
    public PageResponse<RoleVo> selectByPage(RoleDto roleDto, Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize);
        Page<Role> roles = roleMapper.selectByPage(roleDto);
        return PageResponse.of(roles,RoleVo.class);
    }

    @Override
    public List<String> findCheckedResource(Long roleId) {
        List<String> list = roleresourceMapper.findCheckedResource(roleId);
        return list;
    }

    @Transactional
    @Override
    public void update(RoleDto roleDto) {
        //1.修改本表
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);

        if(ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())){
            return;
        }

        //2.修改中间表
        roleresourceMapper.deleteResourceByRoleId(roleDto.getId());
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        ArrayList<RoleResource> list = new ArrayList<>();
        for (String checkedResourceNo : checkedResourceNos) {
            RoleResource resource = RoleResource.builder()
                    .resourceNo(checkedResourceNo)
                    .roleId(roleDto.getId())
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build();
            list.add((resource));
        }


        roleresourceMapper.batchInsert(list);
    }

    @Transactional
    @Override
    public void delete(Long roleId) {
        //删除中间表
        roleresourceMapper.deleteResourceByRoleId(roleId);
        //删除主表
        roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public void addRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public List<RoleVo> initRoles() {
        List<Role> roles = roleMapper.initRoles();
        List<RoleVo> roleVos = BeanUtil.copyToList(roles, RoleVo.class);
        return roleVos;
    }
}
